package com.richest.api.utils;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.richest.api.service.ISysConfigService;
import com.richest.constant.StringConstant;
import com.richest.util.JSONUtil;
import com.richest.util.StringUtil;

import java_cup.runtime.virtual_parse_stack;

/**
 * 图片上传
 * 
 * @author zhaohongchao 2019年4月9日 上午10:47:27
 * @email 70375739@qq.com
 */
@Component
public class OssUploadUtil {
	@Autowired
	private ISysConfigService sysConfigService;

	private static ISysConfigService service;

	@PostConstruct
	private void Init() {
		service = this.sysConfigService;
	}

	public static JSONObject ossupload(String type, String userName, @RequestBody MultipartFile file)
			throws IOException {
		JSONObject resultObject = new JSONObject();
		// String type = servletRequest.getParameter("type");
		// String userName = servletRequest.getParameter("userName");
		String prefix = "";
		if (StringUtil.isNotNullOrEmpty(type)) {
			if (type.equals("1")) {
				prefix = StringConstant.FILE_UPLOAD_ADVERTS;// 广告详情上传图片
			} else if (type.equals("2")) {
				prefix = StringConstant.FILE_UPLOAD_CATEGORY;// 店铺分类图标
			} else if (type.equals("3")) {
				prefix = StringConstant.FILE_UPLOAD_EXTENSION;// 活动详情图片
			} else if (type.equals("4")) {
				prefix = StringConstant.FILE_UPLOAD_USER_HEAD;// 用户头像
			} else if (type.equals("5")) {
				prefix = StringConstant.FILE_UPLOAD_GOOD_IMAGE;// 菜品图片
			} else if (type.equals("6")) {
				prefix = StringConstant.FILE_UPLOAD_ADMART_IMAGE;// 店铺图片
			}
		}
		if (StringUtil.isNotNullOrEmpty(userName)) {
			prefix = prefix + "/" + userName;
		}
		// 如果文件内容不为空，则写入上传路径
		if (!file.isEmpty()) {
			// 上传文件
			// 返回的是一个url对象
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			String url = service.getCloudStorageService().uploadPrefixSuffix(file.getBytes(), prefix, suffix);
			if (StringUtil.isNotNullOrEmpty(url)) {
				resultObject.put("url", url);
				resultObject.put("code", 200);
				resultObject.put("message", "上传成功");
				return resultObject;
			} else {
				resultObject.put("code", 500);
				resultObject.put("message", "上传失败");
				return resultObject;
			}
		}
		return resultObject;
	}
}
